package com.ants.common.utils;

import com.ants.common.exception.AntsException;
import com.aspose.cells.*;
import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;

import java.io.*;

/**
 * TODO
 * Author Chen
 * Date   2023/12/20 9:45
 */
public class ExcelToPdfUtil {

    public static void main(String[] args) {

        String docPath = "F:\\工作簿1.xlsx";
        String pdfPath = "F:\\工作簿1.pdf";
        File pdf = ExcelToPdfUtil.excelToPdf(null, pdfPath);
    }

    /**
     * 加载配置文件
     *
     * @return
     */
    private static boolean getLicense() {
        boolean result = false;
        try (InputStream in = DocToPdfUtil.class.getClassLoader().getResourceAsStream("license.xml")) {
            License license = new License();
            license.setLicense(in);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @param inputStream
     * @param pdfPath
     * @description 如果流不为空则使用转pdf，反之则用docPath进行转pdf
     */
    public static File excelToPdf(InputStream inputStream, String pdfPath) {
        long old = System.currentTimeMillis();
        File pdfFile = new File(pdfPath);
        try (FileOutputStream fos = new FileOutputStream(pdfFile)) {
            // 验证
            if (!getLicense()) {
                throw new AntsException("文件转换失败!");
            }

            Workbook workbook;
            if (inputStream != null) {
                workbook = new Workbook(inputStream);
            } else {
                throw new AntsException("文件转换失败!");
            }
            PdfSaveOptions opts = new PdfSaveOptions();
            // 设置excel不换行在pdf显示
            // opts.setAllColumnsInOnePagePerSheet(true);
            // 设置一个sheet在一页pdf
            opts.setOnePagePerSheet(true);
            workbook.save(fos, opts);
            long now = System.currentTimeMillis();
            System.out.println("pdf转换成功，共耗时：" + ((now - old) / 1000.0) + "秒");
            return pdfFile;
        } catch (Exception e) {
            e.printStackTrace();
            throw new AntsException("文件转换失败!");
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

